package com.kkang.ch1.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 切入切面
 *
 * @author yongk_liu
 **/
@Aspect//使用注解申明这是一个切面
@Component//交给spring管理生命周期
public class LogAspect {

    @Pointcut("@annotation(com.kkang.ch1.aop.Action)")//声明切点，指明使用Action注解方法是连接点
    public void annotationPointCut() {

    }

    @After("annotationPointCut()")//声明一个建言，并使用切点
    public void after(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Action action = method.getAnnotation(Action.class);
        System.out.println("注解式拦截:" + action.name());
    }

    @Before("execution(* com.kkang.ch1.aop.DemoMethodService.*(..))")//声明建言，直接使用拦截规则
    public void before(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        System.out.println("方法式拦截:" + method.getName());
    }

}
